package com.example.memolaga.credentials;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.StringReader;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.example.memolaga.Constants;
import com.example.memolaga.Functions;
import com.example.memolaga.password.FunctionsPass;

import android.util.Log;

public class CredentialManager {
	
	private static CredentialManager instance = null;

	private ArrayList<CredentialMaster> credSaved = null;

	private CredentialManager() { this.credSaved = new ArrayList<CredentialMaster>();};
	
	//private CredentialManager(String xml){loadData(xml);};
	
	//public static CredentialManager getInstance(String xml){if (instance==null) instance = new CredentialManager(xml); return instance;};
	
	public static CredentialManager getInstance(){ if (instance==null) instance = new CredentialManager(); return instance;};
	
	public int addCredFromFile(String path)
    {
        if (!(new File(path).exists())) return 0;
        int size = this.credSaved.size();
        loadData(Functions.getStringOfFile(path));
        return this.credSaved.size()-size;
    }


	public int getNCredentials()
	{
		if (this.credSaved==null) return 0;
		return this.credSaved.size();
	}

    public ArrayList<CredentialMaster> getCredentialSaved() {
        return this.credSaved;
    }

    public ArrayList<CredentialMaster> getCredSaved()
    {
        return this.credSaved;
    }

    public CredentialMaster getCredential(String name)
    {
        if (this.credSaved!=null)
            for(int i=0; i<this.credSaved.size();i++)
                if (name.equals(this.credSaved.get(i).getName()))
                    return this.credSaved.get(i);
        return null;
    }

    public CredentialMaster getCredentialIndex(int i)
    {
        if (i<this.credSaved.size())
            return this.credSaved.get(i);
        else
            return null;
    }



    public String getStringToWrite(ArrayList<CredentialMaster> toWrite)
    {
        String strToWrite = Constants.getHeadXmlFile() + "\n" + Constants.getHeadOpenXML()+Constants.getCredentialsRoot()+Constants.getTailXML() + "\n";
        if (toWrite!=null)
            for (int i=0; i<toWrite.size(); i++)
            {
                CredentialMaster c = toWrite.get(i);
                strToWrite = strToWrite + Constants.getHeadOpenXML()+Constants.getCredentialsElement()+Constants.getTailXML() + "\n";
                strToWrite = strToWrite + Constants.getHeadOpenXML()+Constants.getCredentialsName()+Constants.getTailXML() + c.getName() + Constants.getHeadCloseXML()+Constants.getCredentialsName()+Constants.getTailXML() + "\n";
                strToWrite = strToWrite + Constants.getHeadOpenXML()+Constants.getCredentialsUser()+Constants.getTailXML() + c.getUser() + Constants.getHeadCloseXML()+Constants.getCredentialsUser()+Constants.getTailXML() + "\n";
                strToWrite = strToWrite + Constants.getHeadOpenXML()+Constants.getCredentialsPass()+Constants.getTailXML() + c.getPass() + Constants.getHeadCloseXML()+Constants.getCredentialsPass()+Constants.getTailXML() + "\n";
                strToWrite = strToWrite + Constants.getHeadOpenXML()+Constants.getCredentialsDateCreated()+Constants.getTailXML() + c.getDateCreated() + Constants.getHeadCloseXML()+Constants.getCredentialsDateCreated()+Constants.getTailXML() + "\n";
                strToWrite = strToWrite + Constants.getHeadOpenXML()+Constants.getCredentialsExpiry()+Constants.getTailXML() + c.getDataExpiry() + Constants.getHeadCloseXML()+Constants.getCredentialsExpiry()+Constants.getTailXML()+ "\n";
                strToWrite = strToWrite + Constants.getHeadOpenXML()+Constants.getCredentialsDateLastUsed()+Constants.getTailXML() + c.getDateLastUsed() + Constants.getHeadCloseXML()+Constants.getCredentialsDateLastUsed()+Constants.getTailXML() + "\n";
                strToWrite = strToWrite + Constants.getHeadOpenXML()+Constants.getCredentialsSite()+Constants.getTailXML() + c.getSite() + Constants.getHeadCloseXML()+Constants.getCredentialsSite()+Constants.getTailXML() + "\n";
                strToWrite = strToWrite + Constants.getHeadOpenXML()+Constants.getCredentialsNote()+Constants.getTailXML() + c.getNote() + Constants.getHeadCloseXML()+Constants.getCredentialsNote()+Constants.getTailXML() + "\n";
                strToWrite = strToWrite + Constants.getHeadCloseXML()+Constants.getCredentialsElement()+Constants.getTailXML() + "\n";
            }
        strToWrite = strToWrite + Constants.getHeadCloseXML()+Constants.getCredentialsRoot()+Constants.getTailXML();
        return strToWrite;
    }

    private void loadData(String xml)
    {
        try {

            Log.w("Credentials()", "StartParseXML");
            /** Handling XML */
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            CredentialXMLHandler myXMLHandler = new CredentialXMLHandler();
            xr.setContentHandler(myXMLHandler);

            xr.parse(new InputSource(new StringReader(xml)));
            Log.w("AndroidParseXMLActivity", "Parse3");

            ArrayList<CredentialMaster> itemsList = myXMLHandler.getItemsList();
            if (itemsList.size()>0)
            {
                this.credSaved = new ArrayList<CredentialMaster>();

                for(int i=0;i<itemsList.size();i++){
                    CredentialMaster item = itemsList.get(i);
                    this.credSaved.add(item);
                }

            }
            Log.w("AndroidParseXMLActivity", "Done");
        }
        catch (FileNotFoundException foe)
        {
            Log.i("createFile",foe.getMessage());
        }
        catch (Exception e) {
            Log.w("AndroidParseXMLActivity",e );
        }
    }


    public ArrayList<CredentialMaster> credAdd(String name, String user, String pwd,
                                               String dateCreated, String dateLastUsed,
                                               String expiry, String site, String note, String sKey)
	{
        this.cAdd(name, user, pwd, dateCreated, dateLastUsed, expiry, site, note, sKey);
		return this.credSaved;
	}
	

    public ArrayList<CredentialMaster> credAdd(ArrayList<CredentialMaster> toAdd, String sKey)
    {
        for (int i=0; i<toAdd.size();i++)
            this.cAdd(toAdd.get(i).getName(), toAdd.get(i).getUser(), toAdd.get(i).getPass(),
                    toAdd.get(i).getDateCreated(), toAdd.get(i).getDateLastUsed(), toAdd.get(i).getDataExpiry(),
                    toAdd.get(i).getSite(), toAdd.get(i).getNote(), sKey);
        return this.credSaved;
    }

    public boolean modCredential(String name, String user, String pwd,
                              String dateCreated, String dateLastUsed,
                              String expiry, String site, String note, String sKey)
    {
        for (int i=0;i<this.credSaved.size(); i++)
            if (name.equals(this.credSaved.get(i).getName()))
            {
                CredentialMaster cNew = new CredentialMaster();
                cNew.setName(name);
                cNew.setUser(FunctionsPass.encryptString(sKey, user));
                cNew.setPass(FunctionsPass.encryptString(sKey,pwd));
                cNew.setDateCreated(dateCreated);
                cNew.setDateLastUsed(dateLastUsed);
                cNew.setDataExpiry(expiry);
                cNew.setSite(site);
                cNew.setNote(note);
                this.credSaved.add(i,cNew);
                this.credSaved.remove(i+1);
                return true;
            }
        return false;
    }

    public boolean delCredential(String name)
    {
        for(int i=0; i<this.credSaved.size();i++)
            if (name.equals(this.credSaved.get(i).getName()))
            {
                this.credSaved.remove(i);
                return true;
            }
        return false;
    }

    private void cAdd(String name, String user, String pwd, String dateCreated, String dateLastUsed, String expiry, String site, String note, String sKey)
    {
        CredentialMaster cNew = new CredentialMaster();
        cNew.setName(name);
        cNew.setUser(FunctionsPass.encryptString(sKey, user));
        cNew.setPass(FunctionsPass.encryptString(sKey,pwd));
        cNew.setDateCreated(dateCreated);
        cNew.setDateLastUsed(dateLastUsed);
        cNew.setDataExpiry(expiry);
        cNew.setSite(site);
        cNew.setNote(note);
        this.credSaved.add(cNew);
    }


}
